package com.sc.adminspringboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.adminspringboot.pojo.Posts;
import com.sc.adminspringboot.service.IPostsService;
import com.sc.adminspringboot.utils.ResponseMsg;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 用户发布帖子主表 前端控制器
 * </p>
 *
 * @author 万超凡
 * @since 2025-09-20 10:36:46
 */
@RestController
@RequestMapping("/posts")
public class PostsController {

    @Autowired
    IPostsService postsService;

    /**
     * 分页查询
     *
     * @param page
     * @param limit
     * @param req
     * @return
     */
    @RequestMapping("page")
    ResponseMsg pageQuery(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "20") Integer limit,
                           HttpServletRequest req) {


        IPage<Posts> pageWrapper = new Page<>(page, limit);
        QueryWrapper<Posts> wrapper = new QueryWrapper<>();
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"查询成功",postsService.page(pageWrapper, wrapper));
    }

    /**
     * 联合查询未审核的帖子（包含图片信息）
     *
     * @param page
     * @param limit
     * @param req
     * @return
     */
    @RequestMapping("pendingReview")
    ResponseMsg getPendingReviewPosts(@RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "20") Integer limit,
                                      HttpServletRequest req) {



        try {
            IPage<Posts> pageWrapper = new Page<>(page, limit);
            QueryWrapper<Posts> wrapper = new QueryWrapper<>();
            wrapper.eq("status", 0).orderByDesc("publish_time");
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查询成功", postsService.page(pageWrapper, wrapper));
        } catch (Exception e) {
            System.out.println("查询未审核帖子失败: " + e.getMessage());
            return ResponseMsg.getInstance(ResponseMsg.SERVER_ERROR, "查询失败");
        }
    }

    /**
     * 批量审核通过
     *
     * @param postIds 帖子ID列表
     * @param req
     * @return
     */
    @RequestMapping("batchApprove")
    ResponseMsg batchApprove(@RequestParam List<Integer> postIds, HttpServletRequest req) {



        if (postIds == null || postIds.isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR,"请选择要审核的帖子");
        }

        try {
            boolean success = postsService.batchApprovePosts(postIds);
            if (success) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"批量审核通过成功");
            } else {
                return ResponseMsg.getInstance(ResponseMsg.SERVER_ERROR,"批量审核通过失败");
            }
        } catch (Exception e) {
            System.out.println("批量审核通过失败: " + e.getMessage());
            return ResponseMsg.getInstance(ResponseMsg.SERVER_ERROR,"批量审核通过失败");
        }
    }

    /**
     * 批量拒绝（审核不通过）
     *
     * @param postIds 帖子ID列表
     * @param req
     * @return
     */
    @RequestMapping("batchReject")
    ResponseMsg batchReject(@RequestParam List<Integer> postIds, HttpServletRequest req) {



        if (postIds == null || postIds.isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR,"请选择要拒绝的帖子");
        }

        try {
            boolean success = postsService.batchRejectPosts(postIds);
            if (success) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"批量拒绝成功");
            } else {
                return ResponseMsg.getInstance(ResponseMsg.SERVER_ERROR,"批量拒绝失败");
            }
        } catch (Exception e) {
            System.out.println("批量拒绝失败: " + e.getMessage());
            return ResponseMsg.getInstance(ResponseMsg.SERVER_ERROR,"批量拒绝失败");
        }
    }

    /**
     * 根据帖子ID获取所有图片URL
     *
     * @param postId 帖子ID
     * @param req
     * @return
     */
    @RequestMapping("getImages")
    ResponseMsg getImagesByPostId(@RequestParam Integer postId, HttpServletRequest req) {



        if (postId == null) {
            return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR,"帖子ID不能为空");
        }

        try {
            List<String> imageUrls = postsService.getImageUrlsByPostId(postId);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"查询成功",imageUrls);
        } catch (Exception e) {
            System.out.println("查询图片失败: " + e.getMessage());
            return ResponseMsg.getInstance(ResponseMsg.SERVER_ERROR,"查询图片失败");
        }
    }

    /**
     * 修改状态
     * @param posts
     * @return
     */
    @RequestMapping("update")
    ResponseMsg update(@RequestBody Posts posts) {
        if(posts.getPostId() == null){
            return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR,"帖子的id不能为空");
        }

        postsService.updateById(posts);

        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"修改成功");
    }

    /**
     * 删除
     * <br>
     * 判断status是否为2，如果为2则删除，否则删除失败
     * @param id
     * @param status
     * @return
     */
    @RequestMapping("delete")
    ResponseMsg delete (@RequestParam Integer id,@RequestParam byte status){

        if(id == null){
            return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR,"id不能为空");
        }


        if (status!=0 && status!=1 && status!=2) {
            return ResponseMsg.getInstance(ResponseMsg.NOT_FOUND, "删除失败,帖子不存在");
        }

        if (status == 2) {
            postsService.removeById(id);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "删除成功");
        } else {
            return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR, "删除失败,该帖不处于可删除状态");
        }
    }

    /**
     * 批量删除
     * <br>
     * 仅当所有帖子 status==2（审核不通过）时允许删除
     * @param ids 帖子ID列表
     * @param req HttpServletRequest
     * @return ResponseMsg
     */
    @RequestMapping("batchDelete")
    ResponseMsg batchDelete(@RequestParam List<Integer> ids, HttpServletRequest req) {



        if (ids == null || ids.isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR, "请选择要删除的帖子");
        }

        try {
            // 校验所有待删除帖子均为 status==2
            QueryWrapper<Posts> checkWrapper = new QueryWrapper<>();
            checkWrapper.in("post_id", ids).ne("status", 2);
            long invalidCount = postsService.count(checkWrapper);
            if (invalidCount > 0) {
                return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR, "删除失败,存在非可删除状态的帖子");
            }

            boolean removed = postsService.removeByIds(ids);
            if (removed) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "批量删除成功");
            }
            return ResponseMsg.getInstance(ResponseMsg.SERVER_ERROR, "批量删除失败");
        } catch (Exception e) {
            System.out.println("批量删除失败: " + e.getMessage());
            return ResponseMsg.getInstance(ResponseMsg.SERVER_ERROR, "批量删除失败");
        }
    }

    /**
     * 模糊查询敏感词
     * <br>
     * 在标题与内容中对关键字进行模糊匹配，支持分页
     * @param keyword 关键字
     * @param page 页码
     * @param limit 每页大小
     * @param req HttpServletRequest
     * @return ResponseMsg
     */
    @RequestMapping("searchSensitive")
    ResponseMsg searchSensitive(@RequestParam String keyword,
                                @RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "20") Integer limit,
                                HttpServletRequest req) {



        if (keyword == null || keyword.trim().isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR, "关键字不能为空");
        }

        try {
            IPage<Posts> pageWrapper = new Page<>(page, limit);
            QueryWrapper<Posts> wrapper = new QueryWrapper<>();
            wrapper.and(w -> w.like("title", keyword).or().like("content", keyword));
            wrapper.orderByDesc("publish_time");
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查询成功", postsService.page(pageWrapper, wrapper));
        } catch (Exception e) {
            System.out.println("敏感词模糊查询失败: " + e.getMessage());
            return ResponseMsg.getInstance(ResponseMsg.SERVER_ERROR, "查询失败");
        }
    }

}